#!/bin/bash

# Redis Offline Installation Script
# Function: Compile and install redis 6.x with systemctl service configuration
# Compatible: Anolis OS 7.9 and other offline environments
# Author: System Administrator
# Date: $(date +%Y-%m-%d)
#
# Usage Instructions:
# 1. Place redis-6.x.x.tar.gz (any redis 6.x version) in the same directory as this script
#    Download URL: https://download.redis.io/releases/redis-6.2.14.tar.gz
#    (Note: Script will auto-detect redis 6.x packages, e.g. redis-6.2.9, redis-6.2.14, etc.)
# 2. Install build tools first (script will auto-install, or install manually):
#    - For Anolis OS 7.9: yum install gcc make
#    - For CentOS/RHEL: yum install gcc make
#    - For Ubuntu/Debian: apt-get install gcc make
# 3. Run with root privileges: sudo ./redis_init.sh
# 4. Installation path: /opt/RadMedical/product/tool/redis
#
# IMPORTANT NOTES:
# - Script will auto-install all dependencies before compilation
# - If "C compiler cc is not found" error occurs, install gcc first
# - Script includes gcc and make
# - Compilation process may take a long time
# - Default password: hmgsoft (configured in redis.conf)
# - Bind to localhost IP (127.0.0.1)

set -e  # Exit immediately on error

AUTO_CONFIRM=false

show_usage() {
    cat <<'EOF'
Usage: redis_init.sh [-y]

Options:
  -y    Auto-confirm all interactive prompts (assume "yes")
EOF
}

parse_arguments() {
    while getopts ":yh" opt; do
        case "${opt}" in
            y)
                AUTO_CONFIRM=true
                ;;
            h)
                show_usage
                exit 0
                ;;
            \?)
                log_error "Invalid option: -${OPTARG}"
                show_usage
                exit 1
                ;;
        esac
    done
    shift $((OPTIND - 1))
}

prompt_confirm() {
    local prompt_message="$1"

    if [[ "${AUTO_CONFIRM}" == true ]]; then
        log_info "Auto-confirm enabled (-y). ${prompt_message} -> y"
        REPLY="y"
        return 0
    fi

    read -p "${prompt_message}" -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        return 0
    fi
    return 1
}

# Global variables for redis package detection
REDIS_TAR_FILE=""
REDIS_DIR_NAME=""

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Logging functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root user
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "This script requires root privileges to run"
        exit 1
    fi
}

# Auto-detect redis 6.x package in current directory
detect_redis_package() {
    log_info "Auto-detecting redis 6.x package in current directory..."
    
    # Find redis-6.x.x.tar.gz files
    local redis_packages=($(ls -1 redis-6.*.tar.gz 2>/dev/null | sort -V))
    
    if [[ ${#redis_packages[@]} -eq 0 ]]; then
        log_error "No redis 6.x package found in current directory"
        log_error "Please ensure a redis-6.x.x.tar.gz file exists in the same directory as this script"
        log_error "Download URL: https://download.redis.io/releases/redis-6.2.14.tar.gz"
        exit 1
    fi
    
    if [[ ${#redis_packages[@]} -gt 1 ]]; then
        log_warn "Multiple redis 6.x packages found:"
        for pkg in "${redis_packages[@]}"; do
            log_warn "  - $pkg"
        done
        log_warn "Using the latest version: ${redis_packages[-1]}"
    fi
    
    REDIS_TAR_FILE="${redis_packages[-1]}"
    # Extract directory name from tar file (remove .tar.gz extension)
    REDIS_DIR_NAME="${REDIS_TAR_FILE%.tar.gz}"
    
    log_info "Detected redis package: $REDIS_TAR_FILE"
    log_info "Extracted directory will be: $REDIS_DIR_NAME"
}

# Check if redis source package exists
check_redis_source() {
    # Ensure package is detected
    if [[ -z "$REDIS_TAR_FILE" ]] || [[ -z "$REDIS_DIR_NAME" ]]; then
        log_error "Redis package not detected. Please ensure detect_redis_package() is called first."
        exit 1
    fi
    
    if [[ ! -f "$REDIS_TAR_FILE" ]]; then
        log_error "redis source package $REDIS_TAR_FILE not found, please ensure file is in current directory"
        exit 1
    fi
    log_info "Verified redis source package: $REDIS_TAR_FILE"
}

# Check offline environment
check_offline_environment() {
    log_info "Checking system environment..."
    
    # Detect system type
    if [[ -f /etc/os-release ]]; then
        source /etc/os-release
        log_info "Detected system: $PRETTY_NAME"
        
        if [[ "$ID" == "anolis" ]] || [[ "$ID" == "centos" ]] || [[ "$ID" == "rhel" ]]; then
            log_info "System type: RedHat series (Anolis/CentOS/RHEL)"
            return 0
        elif [[ "$ID" == "ubuntu" ]] || [[ "$ID" == "debian" ]]; then
            log_info "System type: Debian series (Ubuntu/Debian)"
            return 1
        else
            log_warn "Unknown system type: $ID"
            return 2
        fi
    else
        log_warn "Unable to detect system type"
        return 2
    fi
}

# Check necessary build tools
check_build_tools() {
    log_info "Checking build tools..."
    
    local missing_tools=()
    local critical_error=false
    
    # Check C compiler
    if ! command -v gcc >/dev/null 2>&1; then
        missing_tools+=("gcc")
        critical_error=true
    fi
    
    # Check make
    if ! command -v make >/dev/null 2>&1; then
        missing_tools+=("make")
        critical_error=true
    fi
    
    # Check if cc is available (some systems use cc instead of gcc)
    if ! command -v cc >/dev/null 2>&1 && ! command -v gcc >/dev/null 2>&1; then
        log_error "No C compiler found! Neither 'cc' nor 'gcc' is available."
        critical_error=true
    fi
    
    if [[ $critical_error == true ]]; then
        log_error "Critical build tools are missing:"
        for tool in "${missing_tools[@]}"; do
            log_error "  - $tool"
        done
        
        log_info ""
        log_info "SOLUTION: Install the missing tools manually:"
        log_info ""
        log_info "For Anolis OS 7.9 / CentOS / RHEL:"
        log_info "  yum install gcc make"
        log_info ""
        log_info "For Ubuntu / Debian:"
        log_info "  apt-get install gcc make"
        log_info ""
        
        if ! prompt_confirm "Do you want to continue anyway? (y/N): "; then
            log_error "Installation cancelled due to missing critical tools"
            exit 1
        fi
    else
        log_info "Essential build tools check passed"
        
        # Show which compiler will be used
        if command -v gcc >/dev/null 2>&1; then
            log_info "Using GCC compiler: $(gcc --version | head -n1)"
        elif command -v cc >/dev/null 2>&1; then
            log_info "Using CC compiler: $(cc --version | head -n1)"
        fi
    fi
}

# Install dependencies from local source
install_local_dependencies() {
    log_info "=========================================="
    log_info "Installing dependencies from local source"
    log_info "=========================================="
    
    local system_type=$(check_offline_environment)
    
    case $system_type in
        0) # RedHat series
            log_info "Installing dependencies for RedHat series (Anolis/CentOS/RHEL)..."
            
            # Install all required packages directly
            yum install -y gcc make 2>&1 | tee /tmp/redis_deps_install.log || true
            
            if command -v gcc >/dev/null 2>&1; then
                log_info "Successfully installed dependencies: gcc make"
            else
                log_warn "Failed to install dependencies using yum"
                log_warn "Please check the log file: /tmp/redis_deps_install.log"
                log_warn "Try running manually: yum install -y gcc make"
            fi
            ;;
        1) # Debian series
            log_info "Installing dependencies for Debian series (Ubuntu/Debian)..."
            
            # Update package list and install all required packages
            apt-get update 2>&1 | tee /tmp/redis_deps_update.log || true
            apt-get install -y gcc make 2>&1 | tee /tmp/redis_deps_install.log || true
            
            if command -v gcc >/dev/null 2>&1; then
                log_info "Successfully installed dependencies: gcc make"
            else
                log_warn "Failed to install dependencies using apt-get"
                log_warn "Please check the log file: /tmp/redis_deps_install.log"
                log_warn "Try running manually: apt-get install -y gcc make"
            fi
            ;;
        *)
            log_warn "Unknown system type, cannot auto-install dependencies"
            log_warn "Please manually install the following packages:"
            log_warn "  For RedHat series: yum install -y gcc make"
            log_warn "  For Debian series: apt-get install -y gcc make"
            ;;
    esac
    
    log_info "=========================================="
}

# Quick compiler check before starting
quick_compiler_check() {
    log_info "Verifying essential build tools before compilation..."
    
    local has_compiler=false
    local has_make=false
    
    # Check for C compiler
    if command -v gcc >/dev/null 2>&1; then
        log_info "✓ Found GCC compiler: $(gcc --version | head -n1 | awk '{print $3}')"
        has_compiler=true
    elif command -v cc >/dev/null 2>&1; then
        log_info "✓ Found CC compiler: $(cc --version | head -n1 | awk '{print $3}')"
        has_compiler=true
    fi
    
    # Check for make
    if command -v make >/dev/null 2>&1; then
        log_info "✓ Found make tool: $(make --version | head -n1 | awk '{print $3}')"
        has_make=true
    fi
    
    # Critical check - must have both before proceeding
    if [[ $has_compiler == false ]]; then
        log_error "CRITICAL ERROR: No C compiler found!"
        log_error "Neither 'gcc' nor 'cc' is available in the system."
        log_info ""
        log_info "SOLUTION: Install GCC compiler:"
        log_info ""
        log_info "For Anolis OS 7.9 / CentOS / RHEL:"
        log_info "  yum install gcc"
        log_info ""
        log_info "For Ubuntu / Debian:"
        log_info "  apt-get install gcc"
        log_info ""
        log_info "After installing gcc, run this script again."
        log_info ""
        exit 1
    fi
    
    if [[ $has_make == false ]]; then
        log_error "CRITICAL ERROR: make command not found!"
        log_info ""
        log_info "SOLUTION: Install make tool:"
        log_info ""
        log_info "For Anolis OS 7.9 / CentOS / RHEL:"
        log_info "  yum install make"
        log_info ""
        log_info "For Ubuntu / Debian:"
        log_info "  apt-get install make"
        log_info ""
        log_info "After installing make, run this script again."
        log_info ""
        exit 1
    fi
    
    log_info "✓ All build tools verified successfully"
}

# Check system resources
check_system_resources() {
    log_info "Checking system resources..."
    
    # Check disk space
    local available_space=$(df /tmp | awk 'NR==2 {print $4}')
    local required_space=500000  # 500MB in KB
    
    if [[ $available_space -lt $required_space ]]; then
        log_warn "Insufficient disk space: Available ${available_space}KB, Required ${required_space}KB"
        log_warn "Consider cleaning up disk space or choosing another installation location"
    else
        log_info "Disk space check passed: Available ${available_space}KB"
    fi
    
    # Check memory
    local total_mem=$(free -m | awk 'NR==2{print $2}')
    if [[ $total_mem -lt 512 ]]; then
        log_warn "System memory is low: ${total_mem}MB, compilation process may be slow"
    else
        log_info "Memory check passed: ${total_mem}MB"
    fi
    
    # Check CPU core count
    local cpu_cores=$(nproc)
    log_info "CPU core count: $cpu_cores"
    
    log_info "System resource check completed"
}

# Create redis user
create_redis_user() {
    log_info "Creating redis user..."
    
    if id "redis" &>/dev/null; then
        log_warn "redis user already exists"
    else
        useradd -r -s /bin/false -d /var/lib/redis -c "redis user" redis
        log_info "redis user created successfully"
    fi
}

# Extract redis source code
extract_redis_source() {
    log_info "Extracting redis source package..."
    
    if [[ -z "$REDIS_DIR_NAME" ]]; then
        log_error "Redis directory name not detected. Please run detect_redis_package first."
        exit 1
    fi
    
    if [[ -d "$REDIS_DIR_NAME" ]]; then
        log_warn "$REDIS_DIR_NAME directory already exists, removing old directory..."
        rm -rf "$REDIS_DIR_NAME"
    fi
    
    tar -xzf "$REDIS_TAR_FILE"
    cd "$REDIS_DIR_NAME"
    
    log_info "redis source extraction completed"
}

# Compile and install redis
compile_install_redis() {
    log_info "Starting redis compilation..."
    
    # Get CPU core count for parallel compilation
    local cpu_cores=$(nproc)
    log_info "Using $cpu_cores CPU cores for compilation"
    
    # Compilation phase with MAKE variable
    if make -j$cpu_cores; then
        log_info "redis compilation successful"
    else
        log_error "redis compilation failed"
        log_info "Possible causes:"
        log_info "1. Missing necessary build tools"
        log_info "2. Insufficient system resources"
        log_info "3. Corrupted source package"
        log_info ""
        log_info "Suggested solutions:"
        log_info "1. Check if complete build environment is installed"
        log_info "2. Try single-threaded compilation: make"
        log_info "3. Check system memory and disk space"
        exit 1
    fi
    
    log_info "Starting redis installation..."
    if make install PREFIX=/opt/RadMedical/product/tool/redis; then
        log_info "redis installation successful"
    else
        log_error "redis installation failed"
        log_info "Possible causes:"
        log_info "1. Insufficient permissions on target directory"
        log_info "2. Insufficient disk space"
        log_info "3. Incorrect installation path configuration"
        exit 1
    fi
}

# Create necessary directories and set permissions
setup_directories() {
    log_info "Creating necessary directories and setting permissions..."
    
    # Create necessary directories if they don't exist
    mkdir -p /opt/RadMedical/product/tool/redis/{bin,etc,data,log}
    
    # Copy redis executable and tools
    cp src/redis-server /opt/RadMedical/product/tool/redis/bin/
    cp src/redis-cli /opt/RadMedical/product/tool/redis/bin/
    cp src/redis-sentinel /opt/RadMedical/product/tool/redis/bin/ 2>/dev/null || true
    
    # Set ownership and permissions
    chown -R redis:redis /opt/RadMedical/product/tool/redis
    
    # Set directory permissions
    chmod -R 755 /opt/RadMedical/product/tool/redis
    
    # Set specific permissions for binaries
    chmod 755 /opt/RadMedical/product/tool/redis/bin/redis-server
    chmod 755 /opt/RadMedical/product/tool/redis/bin/redis-cli
    
    log_info "Directory permissions setup completed"
}

# Get local IP address
get_local_ip() {
    # Try to get local IP, fallback to 127.0.0.1
    local ip=$(ip route get 8.8.8.8 2>/dev/null | awk '{print $7}' | head -n1)
    if [[ -z "$ip" ]]; then
        ip=$(hostname -I | awk '{print $1}' 2>/dev/null)
    fi
    if [[ -z "$ip" ]]; then
        ip="127.0.0.1"
    fi
    echo "$ip"
}

# Create redis configuration
create_redis_config() {
    log_info "Creating redis configuration..."
    
    local local_ip=$(get_local_ip)
    log_info "Detected local IP: $local_ip"
    
    # Get system memory
    local total_mem=$(free -m | awk 'NR==2{print $2}')
    
    cat > /opt/RadMedical/product/tool/redis/etc/redis.conf << EOF
# Redis Configuration File
# Optimized for: ${total_mem}MB memory
# Generated on: $(date '+%Y-%m-%d %H:%M:%S')

# Network
bind $local_ip
port 6379
protected-mode yes
tcp-backlog 511
timeout 0
tcp-keepalive 300

# General
daemonize yes
supervised systemd
pidfile /opt/RadMedical/product/tool/redis/log/redis.pid
loglevel notice
logfile /opt/RadMedical/product/tool/redis/log/redis.log
databases 16

# Snapshotting
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir /opt/RadMedical/product/tool/redis/data

# Replication
replica-serve-stale-data yes
replica-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
replica-priority 100

# Security
requirepass hmgsoft

# Limits
maxclients 10000

# Memory management
maxmemory-policy noeviction

# Lazy freeing
lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
replica-lazy-flush no

# Append only file
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes

# Lua scripting
lua-time-limit 5000

# Slow log
slowlog-log-slower-than 10000
slowlog-max-len 128

# Latency monitor
latency-monitor-threshold 0

# Event notification
notify-keyspace-events ""

# Advanced config
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
stream-node-max-bytes 4096
stream-node-max-entries 100
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
dynamic-hz yes
aof-rewrite-incremental-fsync yes
rdb-save-incremental-fsync yes
EOF

    # Set proper permissions for config file
    chown redis:redis /opt/RadMedical/product/tool/redis/etc/redis.conf
    chmod 640 /opt/RadMedical/product/tool/redis/etc/redis.conf
    
    log_info "redis configuration created successfully"
}

# Create systemctl service file
create_systemd_service() {
    log_info "Creating systemctl service file..."
    
    cat > /etc/systemd/system/redis.service << 'EOF'
[Unit]
Description=Redis persistent key-value database
After=network.target

[Service]
Type=forking
ExecStart=/opt/RadMedical/product/tool/redis/bin/redis-server /opt/RadMedical/product/tool/redis/etc/redis.conf
ExecStop=/bin/kill -s QUIT $MAINPID
PIDFile=/opt/RadMedical/product/tool/redis/log/redis.pid
TimeoutStopSec=5
Restart=always
RestartSec=10
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755
UMask=007
PrivateTmp=yes
LimitNOFILE=65535

### Security hardening
NoNewPrivileges=true
RestrictRealtime=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX

[Install]
WantedBy=multi-user.target
EOF

    log_info "systemctl service file created successfully"
}

# Configure redis auto-start on boot
enable_redis_service() {
    log_info "Configuring redis auto-start on boot..."
    
    # Reload systemd configuration
    systemctl daemon-reload
    
    # Enable redis service
    systemctl enable redis
    
    log_info "redis auto-start configuration completed"
}

# Start redis service
start_redis_service() {
    log_info "Starting redis service..."
    
    systemctl start redis
    
    # Check service status
    sleep 2
    if systemctl is-active --quiet redis; then
        log_info "redis service started successfully"
    else
        log_error "redis service failed to start"
        systemctl status redis
        exit 1
    fi
}

configure_firewalld_port() {
    local port="6379"
    if ! command -v firewall-cmd >/dev/null 2>&1; then
        log_warn "firewall-cmd 未安装，跳过 firewalld 端口放行。"
        return
    fi

    if systemctl is-active --quiet firewalld; then
        if firewall-cmd --list-ports | grep -qw "${port}/tcp"; then
            log_info "firewalld 已放行端口 ${port}/tcp，跳过配置。"
        else
            log_info "配置 firewalld 放行端口 ${port}/tcp"
            firewall-cmd --permanent --add-port=${port}/tcp
            firewall-cmd --reload
        fi
    else
        log_warn "firewalld 未运行，跳过端口放行步骤。"
    fi
}

# Test redis connection
test_redis() {
    log_info "Testing redis connection..."
    
    sleep 1
    
    # Test connection with password
    if /opt/RadMedical/product/tool/redis/bin/redis-cli -a hmgsoft ping 2>/dev/null | grep -q "PONG"; then
        log_info "redis connection test passed"
    else
        log_warn "redis connection test failed or timed out"
        log_info "This might be normal if redis is still starting up"
    fi
}

# Display installation information
show_installation_info() {
    log_info "=========================================="
    log_info "redis installation completed!"
    log_info "=========================================="
    log_info "Installation path: /opt/RadMedical/product/tool/redis"
    log_info "Configuration file: /opt/RadMedical/product/tool/redis/etc/redis.conf"
    log_info "Data directory: /opt/RadMedical/product/tool/redis/data"
    log_info "Log directory: /opt/RadMedical/product/tool/redis/log"
    log_info ""
    log_info "Configuration Status:"
    log_info "  - Password: hmgsoft"
    log_info "  - Bind IP: $(get_local_ip)"
    log_info "  - Port: 6379"
    log_info ""
    log_info "Service Commands:"
    log_info "  Status: systemctl status redis"
    log_info "  Start:  systemctl start redis"
    log_info "  Stop:   systemctl stop redis"
    log_info "  Restart: systemctl restart redis"
    log_info ""
    log_info "Testing:"
    log_info "  Test connection: /opt/RadMedical/product/tool/redis/bin/redis-cli -a hmgsoft ping"
    log_info "  Interactive: /opt/RadMedical/product/tool/redis/bin/redis-cli -a hmgsoft"
    log_info "=========================================="
}

# Pre-installation check for offline environment
pre_install_check() {
    log_info "=========================================="
    log_info "redis offline installation environment check"
    log_info "=========================================="
    
    # Check system environment
    check_offline_environment
    
    # Check system resources
    check_system_resources
    
    log_info ""
    log_info "Dependency check status:"
    if command -v gcc >/dev/null 2>&1; then
        log_info "✓ gcc compiler: OK - $(gcc --version | head -n1)"
    else
        log_error "✗ gcc compiler: MISSING"
    fi
    
    if command -v make >/dev/null 2>&1; then
        log_info "✓ make tool: OK - $(make --version | head -n1)"
    else
        log_error "✗ make tool: MISSING"
    fi
    
    log_info ""
    log_info "Offline installation instructions:"
    log_info "1. This script is suitable for Anolis OS 7.9 and other offline environments"
    log_info "2. Essential build tools (gcc, make) are required"
    log_info "3. Installation process may take a long time"
    log_info ""
    
    # Final check before proceeding
    if ! command -v gcc >/dev/null 2>&1 || ! command -v make >/dev/null 2>&1; then
        log_error "CRITICAL: Essential build tools are missing!"
        log_error "Please install gcc and make, then run this script again."
        exit 1
    fi
    
    if ! prompt_confirm "All dependencies are ready. Continue installation? (y/N): "; then
        log_info "User cancelled installation"
        exit 0
    fi
    
    log_info "=========================================="
}

# Main function
main() {
    log_info "Starting redis installation..."
    
    # Step 0: Auto-detect redis package first (before any operations)
    log_info "=========================================="
    log_info "Auto-detecting Redis package"
    log_info "=========================================="
    detect_redis_package
    log_info "✓ Redis package auto-detected: $REDIS_TAR_FILE"
    log_info "✓ Extracted directory will be: $REDIS_DIR_NAME"
    log_info ""
    
    # Step 1: Check root privileges first (needed for dependency installation)
    check_root
    log_info "✓ Root privileges verified"
    
    # Step 2: Install dependencies from package manager
    install_local_dependencies
    log_info "✓ Dependency installation attempted"
    
    # Step 3: Critical check - must have gcc and make before proceeding
    log_info ""
    log_info "=========================================="
    log_info "CRITICAL: Verifying build tools are ready"
    log_info "=========================================="
    quick_compiler_check
    
    # Step 4: Pre-installation environment check and user confirmation
    pre_install_check
    
    # Step 5: Verify redis source package exists (already detected in Step 0)
    log_info "=========================================="
    log_info "Preparing Redis compilation"
    log_info "=========================================="
    check_redis_source
    
    # Step 6: Create redis system user
    create_redis_user
    
    # Step 7: Extract redis source code
    extract_redis_source
    
    # Step 8: Compile and install redis (NOW we can compile, all dependencies ready)
    log_info "=========================================="
    log_info "Starting Redis compilation"
    log_info "=========================================="
    compile_install_redis
    
    # Step 9: Setup directory permissions
    setup_directories
    
    # Step 10: Create redis configuration
    create_redis_config
    
    # Step 11: Create systemctl service file
    create_systemd_service
    
    # Step 12: Configure auto-start on boot
    enable_redis_service
    
    # Step 13: Start redis service
    start_redis_service

    # Step 13.5: Configure firewalld port
    configure_firewalld_port
    
    # Step 14: Test redis connection
    test_redis
    
    # Step 15: Display installation information
    show_installation_info
    
    log_info "redis installation script execution completed!"
}

# Execute main function
parse_arguments "$@"
main

